﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace TownsModder.Controls
{
    public class TreeViewWithIcons : TreeViewItem
    {
        #region Global variables

        private readonly Image _icon;
        private readonly TextBlock _textBlock;
        private ImageSource _iconSource;

        #endregion Global variables

        #region Constructors and Destructors

        public TreeViewWithIcons()
        {
            var stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;
            Header = stack;
            //Uncomment this code If you want to add an Image after the Node-HeaderText
            //textBlock = new TextBlock();
            //textBlock.VerticalAlignment = VerticalAlignment.Center;
            //stack.Children.Add(textBlock);
            _icon = new Image();
            _icon.VerticalAlignment = VerticalAlignment.Center;
            _icon.Margin = new Thickness(0, 2, 4, 2);
            _icon.Source = _iconSource;
            stack.Children.Add(_icon);
            //Add the HeaderText After Adding the icon
            _textBlock = new TextBlock();
            _textBlock.VerticalAlignment = VerticalAlignment.Center;
            stack.Children.Add(_textBlock);
        }

        #endregion Constructors and Destructors

        #region Properties

        /// <summary>
        ///     Gets/Sets the Selected Image for a TreeViewNode
        /// </summary>
        public ImageSource Icon
        {
            set
            {
                _iconSource = value;
                _icon.Source = _iconSource;
            }
            get { return _iconSource; }
        }

        #endregion Properties

        #region Event Handlers

        /// <summary>
        ///     Gets/Sets the HeaderText of TreeViewWithIcons
        /// </summary>
        public string HeaderText { set { _textBlock.Text = value + " "; } get { return _textBlock.Text; } }

        /// <summary>
        ///     Event Handler on UnSelected Event
        /// </summary>
        /// <param name="args">Eventargs</param>
        protected override void OnUnselected(RoutedEventArgs args)
        {
            base.OnUnselected(args);
            _icon.Source = _iconSource;
        }

        /// <summary>
        ///     Event Handler on Selected Event
        /// </summary>
        /// <param name="args">Eventargs</param>
        protected override void OnSelected(RoutedEventArgs args)
        {
            base.OnSelected(args);
            _icon.Source = _iconSource;
        }

        #endregion Event Handlers
    }
}